
const db_promise = require("../config/db.config.js");
const logger = require('../util/logger');


async function getSingleSetting(req, res, next) {
  logger.winston.info('settings.getSingleSetting');
  const settingName = req.params.setting_name;
  
  try {
  	
	  const [rows,fields] = await db_promise.query("select * from settings where setting_name = ?",[settingName]);
	
	  res.status(200).json(rows);
  
  }catch(err){

    res.status(400).send({
      message: err
    });  
    return;
	}
	
}

async function getSettings(req, res, next) {
  logger.winston.info('settings.getSettings');
  
  try {
  	  
		  const [rows,fields] = await db_promise.query("select * from settings");
		
		  res.status(200).json(rows);
    
  }catch(err){

    res.status(400).send({
      message: err
    });  
    return;
	}
}

async function updateSetting(req, res, next) {
  logger.winston.info('settings.updateSetting');
  
    try {
    	
			  const [rows,fields] = await db_promise.query("update settings set setting_value = ? where setting_name = ?", [req.body.setting_value, req.body.setting_name]);

        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated' });
			  }else{
			  	  res.status(200).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  
		    return;
	  }
  
}

module.exports = {
  getSingleSetting,
  getSettings,
  updateSetting};
